#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __future__ import division, unicode_literals

import math
from django.shortcuts import render, redirect
from django.contrib import messages
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from office import models
from office import forms
from manager import mytool


@login_required(login_url='/login/')
def list_equipment(request, number=1):
    """ 显示资产列表 """
    username = request.user.username
    list_section = mytool.list_section(number)

    equipments = models.EquipmentModel.objects.all().order_by('-mod_date')

    all_pages = int(math.ceil(len(equipments) / 50))
    columns = list(range(1, all_pages + 1))
    active_page = int(number)
    prev_page = active_page - 1 if (active_page - 1) >= 1 else active_page
    next_page = active_page + 1 if (active_page + 1) <= all_pages\
        else active_page

    equipments = equipments[list_section[0]: list_section[1]]

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'office/equipment/list_equipment.html',
                  request_context)


@login_required(login_url='/login/')
def add_equipment(request):
    """ 新增设备信息 """
    username = request.user.username

    if request.method == 'POST':
        equipment_add_form = forms.EquipmentForm(request.POST)
        number = equipment_add_form.data['number']
        flag = models.EquipmentModel.objects.filter(number=number)

        # 说明该设备信息已经存在
        if flag:
            messages.add_message(request, messages.WARNING, '该设备编号已经存在')

        # 然后判断设备编号是否有效
        elif not mytool.validate_number(number):
            messages.add_message(request, messages.WARNING,
                                 '设备编号只能由数字字母 - 或者 _ 组成')
        # 最后判断其他项是否正确
        elif equipment_add_form.is_valid():

            equipment = equipment_add_form.save(commit=False)
            equipment.creator = username
            equipment.modifier = username
            equipment.save()
            show_id = equipment.id
            messages.add_message(request, messages.SUCCESS, '添加成功')

            return redirect('/office/show_equipment/{0}'.format(show_id))
        else:
            messages.add_message(request, messages.WARNING, '请检查输入的字段')

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'office/equipment/add_equipment.html',
                  request_context)


@login_required(login_url='/login/')
def mod_equipment(request, number):
    """ 修改设备信息 """
    username = request.user.username

    equipment = models.EquipmentModel.objects.filter(number=number)
    equipment = equipment[0]
    show_id = equipment.id

    if request.method == 'POST':
        equipment_mod_form = forms.EquipmentForm(request.POST,
                                                 instance=equipment)
        new_number = equipment_mod_form.data['number']
        flag = models.EquipmentModel.objects.filter(number=new_number)

        if not new_number:
            messages.add_message(request, messages.WARNING,
                                 '设备编号为必填项')

        elif not mytool.validate_number(new_number):
            messages.add_message(request, messages.WARNING,
                                 '设备编号只能由数字字母 - 或者 _ 组成')

        elif flag and new_number != number:
            messages.add_message(request, messages.WARNING,
                                 '该设备编号已经存在')

        elif equipment_mod_form.is_valid():
            equipment = equipment_mod_form.save(commit=False)
            equipment.modifier = username
            equipment.save()
            messages.add_message(request, messages.SUCCESS, '保存成功')

            return redirect('/office/show_equipment/{0}'.format(show_id))
        else:
            messages.add_message(request, messages.WARNING, '请检查输入的字段')

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'office/equipment/mod_equipment.html', locals())


@login_required(login_url='/login/')
def show_equipment(request, _id):
    """ 显示设备信息详情 """
    username = request.user.username
    equipment = []

    if _id.isdigit():
        equipment = models.EquipmentModel.objects.filter(id=_id)

    if not equipment:
        equipment = models.EquipmentModel.objects.filter(number=_id)

    if not equipment:
        return redirect('/office')

    equipment = equipment[0]

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'office/equipment/show_equipment.html',
                  request_context)


@login_required(login_url='/login/')
def search_equipment(request):
    """ 搜索设备信息 """
    username = request.user.username
    equipment_id = request.POST['equipment']
    equipment_id = equipment_id.strip()
    if not equipment_id:
        messages.add_message(request, messages.WARNING,
                             '请输入搜索信息。'
                             '支持输入设备编号(不区分大小写) 或者 '
                             '当前使用者名称关键词 来查询。')
        return redirect('/office')

    equipments = []

    # 首先搜索设备编号
    equipments = models.EquipmentModel.objects.\
        filter(number__icontains=equipment_id)

    # 然后搜索客户名称
    if not equipments:
        equipments = models.EquipmentModel.objects.\
            filter(user__icontains=equipment_id)

    equipments = equipments.order_by('number')

    if not equipments:
        messages.add_message(request, messages.WARNING,
                             '未找到设备信息，请检查输入信息。'
                             '支持输入线路编号(不区分大小写) 或者 '
                             '当前使用者名称关键词 来查询。')
        return redirect('/office')

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'office/equipment/list_search_equipment.html',
                  request_context)


@login_required(login_url='/login/')
def del_equipment(request):
    """ 删除设备信息 """
    username = request.user.username
    equipment_id = request.GET['equipment_id']
    equipment = models.EquipmentModel.objects.filter(id=equipment_id)

    try:
        equipment.delete()
    except Exception:
        messages.add_message(request, messages.WARNING, '删除失败')
    else:
        messages.add_message(request, messages.SUCCESS, '删除成功')

    request_context = RequestContext(request)
    request_context.push(locals())

    # 必须要返回HTTP数据，回调函数才会生效。
    return HttpResponse("操作删除设备信息")
